/*
This file generates the borrower-level regressions in the corporate and 
household credit market with both financial and real outcomes:

	- Table 8: Financial outcomes of households and firms 
	- Table 9: Real outcomes of firms
	- Table 10: Real outcomes of households
	- Table E.1a: Heterogeneity -- MP, firm-size, and financial outcomes
	- Table E.1b: Heterogeneity -- MP, household income, and financial outcomes
*/


// Prepare export of results
global varlabels inter1 "Nonbank x MP Shock" ///
	L.JK_mpshocksign "MP Shock" 

		
/////////////////////////////////////////////////////////////////////////////////
///
/// 					Household credit market 
///
/////////////////////////////////////////////////////////////////////////////////


use if delinquency != 1 using "$procdata/urtepers_panel_ALL.dta", clear 
eststo clear 

// Identify nonbank borrowers
bysort id_borrower year: egen bank_credit = total(REST_GAELD_BLB) if nonbank_lender == 0
bysort id_borrower year: egen nonbank_credit = total(REST_GAELD_BLB) if nonbank_lender == 1
cap drop tot_credit

* make sure that observations that have a missing value for nonbank credit but some bank credit do not get a missing value for nonbank share below
replace bank_credit=0 if bank_credit==.
replace nonbank_credit=0 if nonbank_credit==.
bysort id_borrower year: egen tot_credit = total(REST_GAELD_BLB) if nonbank_lender!=.
bysort id_borrower year: gen nonbank_share = nonbank_credit / tot_credit 


// Collapse data at borrower-year level
local financial_outcomes famqpassivn tot_credit bank_credit nonbank_credit
local real_outcomes famdispon_13 famforbrug1 famboligvaerdi kobtbilvaerdi famnyformue
local all_outcomes `financial_outcomes' `real_outcomes'

gcollapse (lastnm)  `real_outcomes' JK_mpshocksign DK_* vix   ///
	(max) `financial_outcomes' nonbank_share , by(id_borrower year) 
	
xtset id_borrower year		
		
		
//////////////////////////////////////////////////////////////////
/// Table 8.a: Financial outcomes at household-level
//////////////////////////////////////////////////////////////////

// Create outcome variables  
qui foreach var in  `all_outcomes' {
	gen log_`var' = log(`var')
	}


eststo clear

* Regress financial outcomes on lagged MP shock
local RHSvars L.JK_mpshocksign L.DK_real_gdp_grate L.DK_gdp_growth_forecast /// 
	L.DK_inflation_rate L.vix 
local regopts noconstant a(id_borrower) vce(cluster id_borrower)
	
foreach outcome of local financial_outcomes  {
	 
	 eststo fin_`outcome': qui reghdfe log_`outcome' `RHSvars', `regopts'

	}

eststo fin_bank_credit_pure: qui reghdfe log_bank_credit `RHSvars' if nonbank_share == 0, `regopts'		
eststo fin_nonbank_credit_pure: qui reghdfe log_nonbank_credit  `RHSvars' if nonbank_share == 1,  `regopts'
		
* Export results to panel a of Table 8 (to be completd further below)		
qui estadd local MacroControls "Yes": *
qui estadd local BorrowerFE "Yes": *

local stats_BorFE_BorClust N r2 MacroControls BorrowerFE  
local label_BorFE_BorClust `""Observations" "R2" "Macro Controls"  "Borrower FE"  "'

esttab fin_*,   varwidth(25) keep(L.JK_mpshocksign) /// 
		 transform((exp(@)-1)*100 100*exp(@)) star(* 0.10 ** 0.05 *** 0.01) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels($varlabels) collabels(none) ///
		stats(`stats_BorFE_BorClust', labels(`label_BorFE_BorClust')  fmt(%12.0fc 2)) ///
		mtitles("Ln Debt" "Ln Credit" "Leverage" "Ln Bank Credit" ///
		"Ln Nonbank Credit" "Ln Bank Credit Pure" "Ln Nonbank Credit Pure" ) 


esttab fin_* using "$tables/Regression_FinancialEffects_consolidated.tex", ///
		booktabs fragment varwidth(25) keep(L.JK_mpshocksign) collabels(none) /// 
		prehead("\begin{tabular}{l*{6}{cc}} \toprule") ///
		posthead("\hline \\ \multicolumn{4}{l}{\textbf{Panel A. Households}} \\\\[-1ex]") ///
		transform((exp(@)-1)*100 100*exp(@)) star(* 0.10 ** 0.05 *** 0.01) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels($varlabels)  ///
		stats(`stats_BorFE_BorClust', labels(`label_BorFE_BorClust')  fmt(%12.0fc 2)) ///
		mtitles("Ln Debt" "Ln Credit" "Ln Bank Credit" ///
		"Ln Nonbank Credit" "Ln Bank Credit Pure" "Ln Nonbank Credit Pure") replace		
		
		
		
//////////////////////////////////////////////////////////////////
/// Table 10: Real outcomes of households
//////////////////////////////////////////////////////////////////

cap drop nonbank_history
cap drop inter*

// Generate an indicator if borrower has had a nonbank relationship in the past
gen byte nonbank_history = 1 if L.nonbank_share > 0.5  & L.nonbank_share != .
replace nonbank_history = 0 if nonbank_history == .

*interaction terms
gen inter1=nonbank_history*L.JK_mpshocksign
gen inter2=nonbank_history*L.DK_real_gdp_grate
gen inter3=nonbank_history*L.DK_gdp_growth_forecast
gen inter4=nonbank_history*L.DK_inflation_rate
gen inter5=nonbank_history*L.vix

 		
eststo clear
foreach outcome of local real_outcomes {

	 eststo real_`outcome': qui reghdfe log_`outcome' L.JK_mpshocksign inter1-inter5 ///
	 , noconstant a(id_borrower) vce(cluster id_borrower)
}

qui estadd local MacroControlsInt "Yes": *
qui estadd local BorrowerFE "Yes": *

local stats_BorFE_BorClust N r2 MacroControlsInt  BorrowerFE  
local label_BorFE_BorClust `""Observations" "R2" "Macro Control Interactions"  "Borrower FE"  "'


esttab real_*,   varwidth(25) star(* 0.10 ** 0.05 *** 0.01) collabels(none) ///
		keep(L.JK_mpshocksign inter1) transform((exp(@)-1)*100 100*exp(@)) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels($varlabels)  ///
		stats(`stats_BorFE_BorClust', labels(`label_BorFE_BorClust')  fmt(%12.0fc 2)) ///
		mtitles("Disp. Income"  "Consumption" "MV RE" "MV New Cars" "MV Total Assets") 
		

esttab using "${tables}/URTEPERS_Regression_RealEffects.tex", collabels(none) ///
		booktabs  varwidth(25) keep(L.JK_mpshocksign inter1) /// 
		 transform((exp(@)-1)*100 100*exp(@)) star(* 0.10 ** 0.05 *** 0.01) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels($varlabels)  ///
		stats(`stats_BorFE_BorClust', labels(`label_BorFE_BorClust')  fmt(%12.0fc 2)) ///
		mtitles("Disp. Income"  "Consumption" "MV RE" "MV New Cars" "MV Total Assets") replace


//////////////////////////////////////////////////////////////////
/// Table E.1b: Heterogeneity -- MP, household income, and financial outcomes
//////////////////////////////////////////////////////////////////

* Create quintiles of disposable income distribtuion 
gquantiles famdispon_quintiles = famdispon_13, xtile n(5) by(year)
eststo clear

foreach outcome of local financial_outcomes  { // 
	
	local macrovars  DK_real_gdp_grate DK_gdp_growth_forecast	 DK_inflation_rate vix
	local reg_model qui reghdfe log_`outcome' L.famdispon_quintiles##cL.JK_mpshocksign L.(`macrovars') 
	local reg_opts noconstant  a(id_borrower) vce(cluster id_borrower)
	
	eststo `outcome': 	`reg_model', `reg_opts' 
	
} 

* Save results
qui estadd local MacroControls "Yes": *
qui estadd local BorrowerFE "Yes": *

local varlabels_income ///
		2L.famdispon_quintiles#cL.JK_mpshocksign "Disp. income p20-p40 x MP Shock" ///
		3L.famdispon_quintiles#cL.JK_mpshocksign "Disp. income p40-p60 x MP Shock" ///
		4L.famdispon_quintiles#cL.JK_mpshocksign "Disp. income p60-p80 x MP Shock" ///
		5L.famdispon_quintiles#cL.JK_mpshocksign "Disp. income p80-p100 x MP Shock" 
		
local stats_TestFE  N r2 MacroControls  BorrowerFE
local label_TestFE `""Observations" "R2" "Macro controls"  "Borrower FE" "'

local table_opts booktabs  varwidth(25) keep(*L.famdisp*#cL.JK_mpshocksign) /// 
		 transform((exp(@)-1)*100 100*exp(@)) star(* 0.10 ** 0.05 *** 0.01) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels(`varlabels_income')  ///
		stats(`stats_TestFE', labels(`label_TestFE')  fmt(%12.0fc 2)) ///
		mtitles("Ln Debt" "Ln Credit" "Ln Bank Credit" ///
		"Ln Nonbank Credit") collabels(none)

esttab *, `table_opts'
esttab using "$tables/PERS_Regression_HHlvl_bydispinc_reldiff.tex", `table_opts' replace
			
	
		
		
/////////////////////////////////////////////////////////////////////////////////
///
/// 					Corporate credit market 
///
/////////////////////////////////////////////////////////////////////////////////


use if delinquency != 1 using "${procdata}/URTEVIRK_FIRE_FIRM_03-18.dta", clear 


* Identify nonbank borrowers 
bysort id_borrower year: egen bank_credit = total(REST_GAELD_BLB) if nonbank_lender == 0
bysort id_borrower year: egen nonbank_credit = total(REST_GAELD_BLB) if nonbank_lender == 1

* make sure that observations that have a missing value for nonbank credit but ///
* some bank credit do not get a missing value for nonbank share below
replace bank_credit=0 if bank_credit==.
replace nonbank_credit=0 if nonbank_credit==.

bysort id_borrower year: egen tot_credit = total(REST_GAELD_BLB) 
bysort id_borrower year: gen nonbank_share = nonbank_credit / tot_credit 

* generate total debt
gen tot_debt = GF_AT - GF_EGUL if GF_EGUL >= 0 & !mi(GF_EGUL)

// Collapse data at borrower-year level
local financial_outcomes tot_debt tot_credit bank_credit nonbank_credit
local real_outcomes GF_AT  atit GF_RFEP GF_LGAGMV
local all_outcomes `financial_outcomes' `real_outcomes'

gcollapse (lastnm) `real_outcomes' JK_mpshocksign DK_* vix GF_OMS    ///
	(max) `financial_outcomes' nonbank_share , by(id_borrower year) 
	
xtset id_borrower year

// Create outcome variables 
qui foreach var of local all_outcomes {
	gen log_`var' = log(`var')
}



//////////////////////////////////////////////////////////////////
/// Table 8.b: Financial outcomes at firm-level 
//////////////////////////////////////////////////////////////////

* Regress financial outcomes on lagged MP shock 		
eststo clear

local RHSvars L.JK_mpshocksign L.DK_real_gdp_grate L.DK_gdp_growth_forecast /// 
	L.DK_inflation_rate L.vix 
	
local regopts noconstant a(id_borrower) vce(cluster id_borrower)
	
foreach outcome of local financial_outcomes {
	 eststo fin_`outcome': qui reghdfe log_`outcome' `RHSvars', `regopts'
}

eststo fin_bank_credit_pure: qui reghdfe log_bank_credit `RHSvars' if nonbank_share == 0, `regopts'	
eststo fin_nonbank_credit_pure: qui reghdfe log_nonbank_credit `RHSvars' if nonbank_share == 1, `regopts'	


* Append results to panel b of table that we created further above	
qui estadd local MacroControls "Yes": *
qui estadd local BorrowerFE "Yes": *

local stats_BorFE_BorClust N r2 MacroControls BorrowerFE  
local label_BorFE_BorClust `""Observations" "R2" "Macro Controls"  "Borrower FE"  "'


esttab fin_*,   varwidth(25) keep(L.JK_mpshocksign) collabels(none) /// 
		 transform((exp(@)-1)*100 100*exp(@)) star(* 0.10 ** 0.05 *** 0.01) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels($varlabels)  ///
		stats(`stats_BorFE_BorClust', labels(`label_BorFE_BorClust')  fmt(%9.0fc 2)) ///
		nonum nomtitles append
		
esttab fin_* using "$tables/Regression_FinancialEffects_consolidated.tex", ///
		booktabs fragment varwidth(25) keep(L.JK_mpshocksign) collabels(none) /// 
		 transform((exp(@)-1)*100 100*exp(@)) star(* 0.10 ** 0.05 *** 0.01) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels($varlabels)  ///
		posthead("\hline \\ \multicolumn{4}{l}{\textbf{Panel B. Firms}} \\\\[-1ex]") ///
		stats(`stats_BorFE_BorClust', labels(`label_BorFE_BorClust')  fmt(%9.0fc 2)) ///
		append nomtitles nonum ///
		postfoot("\hline\hline \end{tabular}")
		
		
	
//////////////////////////////////////////////////////////////////
/// Table 9: Real outcomes of firms 
//////////////////////////////////////////////////////////////////

cap drop nonbank_history
cap drop inter*

// Generate an indicator if borrower has had a nonbank relationship in the past
gen byte nonbank_history = 1 if L.nonbank_share > 0.5  & L.nonbank_share != .
replace nonbank_history = 0 if nonbank_history == . & L.nonbank_share <0.5 & L.nonbank_share != .

*interaction terms
// MP shock measures
gen inter1=nonbank_history*L.JK_mpshocksign
gen inter2=nonbank_history*L.DK_real_gdp_grate
gen inter3=nonbank_history*L.DK_gdp_growth_forecast
gen inter4=nonbank_history*L.DK_inflation_rate
gen inter5=nonbank_history*L.vix

* Regress real outcomes on lagged MP shock & interaction with indicator for nonbank borrowers		
eststo clear

foreach outcome of local real_outcomes {

	 eststo real_`outcome': qui reghdfe log_`outcome' L.JK_mpshocksign inter1-inter5 ///
	 , noconstant a(id_borrower) vce(cluster id_borrower)
}

* Export results 
qui estadd local MacroControlsInt "Yes": *
qui estadd local BorrowerFE "Yes": *

local stats_BorFE_BorClust N r2 MacroControlsInt  BorrowerFE  
local label_BorFE_BorClust `""Observations" "R2" "Macro Control Interactions"  "Borrower FE"  "'


esttab real_*,   varwidth(25) star(* 0.10 ** 0.05 *** 0.01) collabels(none) ///
		keep(L.JK_mpshocksign inter1) transform((exp(@)-1)*100 100*exp(@)) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels($varlabels)  ///
		stats(`stats_BorFE_BorClust', labels(`label_BorFE_BorClust')  fmt(%9.0fc 2)) ///
		mtitles("Tot. Assets" "Investment"  "Oper. Profit"  "Wage Bill") 


esttab using "$tables/FIRMS_Regression_RealEffects.tex", star(* 0.10 ** 0.05 *** 0.01) ///
		booktabs  varwidth(25) keep(L.JK_mpshocksign inter1) /// 
		 transform((exp(@)-1)*100 100*exp(@))  collabels(none) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels($varlabels)  ///
		stats(`stats_BorFE_BorClust', labels(`label_BorFE_BorClust')  fmt(%9.0fc 2)) ///
		mtitles("Tot. Assets" "Investment" "Oper. Profit"  "Wage Bill") replace

		
		
//////////////////////////////////////////////////////////////////
/// Table E.1a: Heterogeneity -- MP, firm-size, and financial outcomes
//////////////////////////////////////////////////////////////////

* Create quintiles of firm size (sales) distribution 
gquantiles Sales_quintiles = GF_OMS, xtile n(5) by(year)

* Regress financial outcomes on lagged MP shock 
eststo clear 
local financial_outcomes tot_debt tot_credit bank_credit nonbank_credit

foreach outcome of local financial_outcomes  { // 
	
	local macrovars  DK_real_gdp_grate DK_gdp_growth_forecast	 DK_inflation_rate vix
	local reg_model qui reghdfe log_`outcome' L.Sales_quintiles##cL.JK_mpshocksign L.(`macrovars') 
	local reg_opts noconstant  a(id_borrower) vce(cluster id_borrower)
	
	eststo `outcome': 	`reg_model', `reg_opts' 
	
} 

qui estadd local MacroControls "Yes": *
qui estadd local BorrowerFE "Yes": *

local varlabels_sales  ///
		2L.Sales_quintiles#cL.JK_mpshocksign "Sales p20-p40 x MP Shock" ///
		3L.Sales_quintiles#cL.JK_mpshocksign "Sales p40-p60 x MP Shock" ///
		4L.Sales_quintiles#cL.JK_mpshocksign "Sales p60-p80 x MP Shock" ///
		5L.Sales_quintiles#cL.JK_mpshocksign "Sales p80-p100 x MP Shock" 
		
local stats_TestFE  N r2 MacroControls  BorrowerFE
local label_TestFE `""Observations" "R2" "Macro controls"  "Borrower FE" "'

local table_opts booktabs  varwidth(25) keep(*L.Sales_*#cL.JK_mpshocksign) /// 
		 transform((exp(@)-1)*100 100*exp(@)) star(* 0.10 ** 0.05 *** 0.01) /// 
		cells(b(star fmt(2)) se(fmt(2) par)) varlabels(`varlabels_sales') collabels(none)  ///
		stats(`stats_TestFE', labels(`label_TestFE')  fmt(%9.0fc 2)) ///
		mtitles("Ln Debt" "Ln Credit" "Ln Bank Credit" ///
		"Ln Nonbank Credit") 

esttab *, `table_opts'
esttab using "$tables/FIRMS_Regression_firmlvl_bysales_reldiff.tex", `table_opts' replace